<?php

	/**
	 * Crawls wine item from http://api.wine-searcher.com
	 *
	 * @author anton.perkin
	 * @version 1.0
	 *
	 */
	class WineSearcher implements WineSource
	{
		/* VARIABLES */
		
		/**
		 * Vintages URL
		 *
		 * @var string
		 */
		public $vintagesURL = 'http://api.wine-searcher.com/wine-select-api.lml?Xaffiliate=vineloop&Xversion=4&Xwinename=*%20cellars&Xvintage=&Xlocation=usa&Xautoexpand=Y&Xcurrencycode=usd&Xkeyword_mode=A';
		
		/**
		 * Wine list base URL
		 *
		 * @var string
		 */
		public $winesURL = 'http://api.wine-searcher.com/wine-select-api.lml?Xaffiliate=vineloop&Xversion=4&Xwinename=*%20cellars&Xvintage=#&Xlocation=usa&Xautoexpand=Y&Xcurrencycode=usd&Xkeyword_mode=A';
		
		/**
		 * Wine URLs
		 *
		 * @var array
		 */
		public $wineURLs;
		
		
		/* CONSTRUCTORS */
			
		/**
		 * Defualt constructor
		 *
		 */
		public function WineSearcher()
		{

		}		
		
		
		/* METHODS */
		
		/**
		 * Gets and saves wine vintages
		 *
		 * @param int $fromPageNumber from page
		 * @param int $toPageNumber to page
		 * 
		 */
		public function GetAndSaveVintages($fromRecord, $toRecord)
		{
			$result = array('success' => 0, 'fail' => 0);
			
			//limit
			if (($fromRecord == '') && ($toRecord == ''))
			{
				$limit = '';
			}
			else 
			{
				$fromRecord = ($fromRecord == '') ? 0 : $fromRecord;
				$toRecord = ($toRecord == '') ? 1000000 : $toRecord;
				$limit = "LIMIT $fromRecord, $toRecord";
			}			
			
			$wineries = DB::ListItems("
				SELECT * FROM t_wineries $limit;
			");

			foreach ($wineries as $winery)
			{
				$page = phpQuery::newDocumentFileXML(str_replace('*', urlencode($winery['name']), $this->vintagesURL));
				
				$vintages = $page->find("wine-vintages");
				
				foreach (pq($vintages)->children() as $vintage)
				{
					$year = pq($vintage)->find('vintage')->html();
					if ($year != '0' && $year != '2')
					{
						if (DB::ExecuteSQL("
							INSERT INTO t_winery_vintages
							(
								winery_id,
								winery_name,
								year
							)
							VALUES
							(
								{$winery['id']},
								'".addslashes($winery['name'])."',
								'$year'
							);
								
						") === true)
						{
							$this->LogVintage($winery['name'], $year, true);
							$result['success']++;
						}	
						else 
						{
							$this->LogVintage($winery['name'], $year, false);
							$result['fail']++;
						}		
					}
				}
			}
			return $result;			
		}

		/**
		 * Gets wines URLs list
		 *
		 * @param int $fromRecord offset
		 * @param int $toRecord count
		 */
		public function GetSavedVintages($fromRecord = '', $toRecord = '')
		{
			//limit
			if (($fromRecord == '') && ($toRecord == ''))
			{
				$limit = '';
			}
			else 
			{
				$fromRecord = ($fromRecord == '') ? 0 : $fromRecord;
				$toRecord = ($toRecord == '') ? 1000000 : $toRecord;
				$limit = "LIMIT $fromRecord, $toRecord";
			}
			
			$urls = DB::ListItems("
				SELECT * FROM t_winery_vintages $limit;
			");
			
			return $urls;
		}		
		
		/**
		 * Gets WineItem
		 * 
		 * @param int $id wine id
		 * 
		 * @return WineItem
		 *
		 */
		function GetWineItem($id)
		{
			
		}

		/**
		 * Gets wine items
		 * 
		 * @param array $vintage vintage
		 * 
		 * @return array
		 *
		 */
		function GetWineItems($vintage)
		{
			$items = array();
			
			$url = str_replace('*', urlencode($vintage['winery_name']), $this->winesURL);
			$url = str_replace('#', urlencode($vintage['year']), $url);

			$page = phpQuery::newDocumentFileXML($url);
			
			$wines = $page->find("wines");

			foreach (pq($wines)->children() as $wine)
			{
				//wine item
				$wineItem = new WineItem();
				
				//url parse
				$url = html_entity_decode(pq($wine)->find('link')->html());
				$parsedURL = parse_url($url);
				parse_str($parsedURL['query'], $urlParams);
				
				//wine details
				$wineItem->id = $urlParams['wine_id_F'];
				$wineItem->name = html_entity_decode(pq($wine)->find('wine-description')->html());
				$wineItem->displayName = html_entity_decode(pq($wine)->find('wine-description')->html());
				$wineItem->vintage = pq($wine)->find('vintage')->html();
				$wineItem->producer = html_entity_decode(pq($wine)->find('merchant')->html());
				$wineItem->webAddress = $url;
				$wineItem->source = 'wine-searcher';
				$wineItem->region = pq($wine)->find('state')->html();
				$wineItem->urlId = 0;
				$wineItem->tableName = 't_wines_2';
				
				$items[] = $wineItem;
			}

			return $items;
		}
		
		
		/**
		 * Creates log entry for the inserted record
		 *
		 * @param string $winery winery
		 * @param string $year year
		 * @param boolean $success result
		 */
		private function LogVintage($winery, $year, $success)
		{
			$color = ($success) ? 'green' : 'red';
			
			echo "<span style = 'color: $color; '>
			Winery: $winery | Year: $year
			</span><br />";
		}		
		
	}

?>